const MYSQL = require("../../sql/mysql");
// MYSQL数据库配置信息
const MYSQLConfig = require("../../sql/database");
let sqlName = MYSQLConfig.datasheetName.roles;
/**
 * 角色是否存在
 * @param {object} params
 * @param {string} params.id 角色id
 * @param {string} params.name 角色名称
 * @returns {Promise<{code:string,msg:string,exist:boolean}>}
 */
module.exports = async (params = {}) => {
  try {
    let { id, name, scope } = params;
    let query = `SELECT * FROM ${sqlName} WHERE `;
    if (id) {
      query += `id = ${id}`;
    } else if (name) {
      query += `name = '${name}'`;
    } else if (scope) {
      query += `scope = '${scope}'`;
    }else {
      throw {
        code: 500,
        msg: "暂不支持该方式获取用户信息",
      };
    }
    let roles = null;
    try {
      roles = await MYSQL.queryPromise(query);
    } catch (err) {
      throw {
        code: 200,
        msg: "查询失败，数据库操作不成功",
      };
    }
    if (roles.length) {
      let roleInfo = roles[0];
      let { state } = roleInfo;
      if (state == 1) {
        return {
          code: 0,
          msg: "获取成功",
          exist: true,
          length: roles.length,
          roleInfo,
        };
      } else {
        throw {
          code: 500,
          msg: "角色状态不可用",
          exist: false,
          length: 0,
          roleInfo: {},
        };
      }
    } else {
      throw {
        code: 500,
        msg: "角色不存在",
        exist: false,
        length: 0,
        roleInfo: {},
      };
    }
  } catch (error) {
    throw error;
  }
};
